package com.example.servlet;

//import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.config.AlipayConfig;
import com.example.dao.NovelDao;
import com.example.domain.Chapter;
import com.example.domain.OrderRecord;
import org.json.JSONObject;
import org.json.JSONException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.concurrent.TimeUnit;

@WebServlet("/AlipayServlet")
public class AlipayServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        // 添加日志输出，帮助调试
        System.out.println("开始处理支付请求...");
        // 从请求中获取数据
        BufferedReader reader = request.getReader();
        String jsonStr = reader.lines().collect(Collectors.joining());
        // 使用 JSONObject 解析 JSON 字符串
        JSONObject jsonObj = new JSONObject(jsonStr);

        System.out.println("收到的JSON数据: " + jsonStr);  // 打印接收到的数据
        // 获取所有传递的参数
        String chapterId = jsonObj.getString("chapter_id");
        String chapterTitle = jsonObj.getString("chapter_title");
        String novelName = jsonObj.getString("novel_name");
        String userId = jsonObj.getString("user_id");
        String novel_id = jsonObj.getString("novel_id");
//        List<Chapter> chapterList = JSON.parseArray(jsonObj.getString("chapterList"), Chapter.class);
        double price = Double.parseDouble(jsonObj.getString("price"));
        String subject = jsonObj.getString("subject");
        String body = jsonObj.getString("body");

        try {
            // 创建订单记录
            OrderRecord order = new OrderRecord();
            order.setOrder_no(generateOrderNo(chapterId,novel_id));
            order.setChapter_id(chapterId);
            order.setNovel_name(novelName);
            order.setChapter_title(chapterTitle);
            order.setPrice(price);
            order.setUser_id(userId);

            NovelDao novelDao = new NovelDao();
        // 打印订单信息
            System.out.println("订单信息: " + order.toString());
        // 保存订单到数据库
            if (!novelDao.saveOrderRecord(order)) {
                throw new Exception("保存订单失败");
            }
            // 配置支付宝参数并生成支付表单
            AlipayClient alipayClient = new DefaultAlipayClient(
                    AlipayConfig.gatewayUrl,
                    AlipayConfig.app_id,
                    AlipayConfig.merchant_private_key,
                    "json",
                    AlipayConfig.charset,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.sign_type
            );

            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", order.getOrder_no());
            bizContent.put("total_amount", price);
//            bizContent.put("novel_id", novel_id);
            bizContent.put("subject", subject);
            bizContent.put("body", body);
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

//            HttpSession session = request.getSession();
//            // 将章节列表存入session
//            List<Chapter> chapterList= (List<Chapter>) session.getAttribute("chapterList");
//
//            session.setAttribute("chapterList",chapterList);
            alipayRequest.setBizContent(bizContent.toString());

            String form = alipayClient.pageExecute(alipayRequest).getBody();

//            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(form);

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            response.getWriter().write("生成支付订单失败");
        }
    }

    private String generateOrderNo(String chapterId,String novelId) {
        return System.currentTimeMillis()+"-"+chapterId+"#"+novelId;
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}